<template>
  <div>
    <el-container>
      <el-header>
        <img src="https://csdnimg.cn/cdn/content-toolbar/csdn-logo.png?v=20200416.1" />
      </el-header>
      <el-main>
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="ruleForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="ruleForm.password"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
            <el-button @click="register">注册</el-button>
          </el-form-item>
        </el-form>
      </el-main>
    </el-container>
  </div>
</template>
<script>
export default {
  name: "login",
  data() {
    return {
      ruleForm: {
        username: "xiaoming",
        password: "111111",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "change" },
          { min: 6, message: "密码不能低于6位", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
            var vm = this;
          this.$axios({
            method: "POST",
            url: "/login",
            data: vm.ruleForm
          }).then(function (response) {

            console.log(response);
            const jwt = response.headers["token"];
            const userInfo = response.data.data;
            //把数据共享出去
            vm.$store.commit("SET_TOKEN",jwt);
            vm.$store.commit("SET_USERINFO",userInfo);

            console.log(vm.$store.getters.getUser);

            vm.$router.push("/blogs");
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    register() {
      this.$router.push("/register");
    },
  },
};
</script>
<style>
.el-header,
.el-footer {
  /* background-color: #B3C0D1; */
  /* color: #333; */
  text-align: center;
  line-height: 60px;
}

.el-aside {
  background-color: #d3dce6;
  color: #333;
  text-align: center;
  line-height: 200px;
}

.el-main {
  /* background-color: #E9EEF3; */
  /* color: #333; */
  text-align: center;
  line-height: 160px;
}

body > .el-container {
  margin-bottom: 40px;
}

.el-container:nth-child(5) .el-aside,
.el-container:nth-child(6) .el-aside {
  line-height: 260px;
}

.el-container:nth-child(7) .el-aside {
  line-height: 320px;
}

.demo-ruleForm {
  margin: 0 auto;
  max-width: 500px;
}
</style>